package com.gm.commonlib.base.baseui.baseListviewUI;

import android.annotation.SuppressLint;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.gm.commonlib.R;
import com.gm.commonlib.application.MyApplicationHolder;
import com.gm.commonlib.base.baseBean.BasePageListData;
import com.gm.commonlib.base.baseBean.BaseResp;
import com.gm.commonlib.base.baseBean.BaseListResp;
import com.gm.commonlib.base.baseBean.DataResp;
import com.gm.commonlib.base.baseBean.PageData;
import com.gm.commonlib.base.baseBean.PageInfo;
import com.gm.commonlib.network.BaseHttpObserver;
import com.gm.commonlib.network.HttpClient;
import com.gm.commonlib.network.HttpResultCode;
import com.gm.commonlib.network.HttpServicesHolder;
import com.gm.commonlib.views.toast.ToastUtil;

import java.util.ArrayList;
import java.util.List;

abstract class BasePullToRefeshActivity <
       DataType,
       NetworkResponse>
       extends BasePullToRefeshViewActivity {

   protected PageInfo mPageInfo = null;
   protected List<DataType> mDatas = new ArrayList<>();
   public  boolean isEnterGetData = true;
   public long mCurrentPage=1;
   protected BaseAdapter mBaseAdapter = null;



   protected abstract HttpServicesHolder<?, NetworkResponse> getHttpServicesHolder(long page);
   public boolean getIsEnterGetData() {
       return true;
   }



   /**
    * 创建界面Item的适配器
    *
    * @return 适配器
    */
   protected abstract BaseAdapter createTempBaseAdapter();




   protected void requestPageData(long pageNo, final boolean fresh) {
      // showLoadingDialog();
       startGetData();
       HttpClient.sendRequest(null, fresh, getHttpServicesHolder(pageNo), new BaseHttpObserver<NetworkResponse>() {
           @Override
           public void onCompleted() {
               super.onCompleted();
               hidLoadingDialog();
               getDataOnCompleted();
               resetPullToRefreshListView();

           }

           @Override
           public void onNext(NetworkResponse resp) {
               BaseResp baseResp=((BaseResp) resp);
               if (baseResp.getCode()== HttpResultCode.TOKEN_ERROR.getCode()
               || baseResp.getCode()==HttpResultCode.OTHER_LOGIN.getCode()){
                   MyApplicationHolder.getApplication().login(baseResp.getCode());
               }

               else {
                   getDataOnNext(resp,isRefresh);
               }

           }

           @Override
           protected void onError(String error) {
               //此处为出现异常或者网络错误回调
               //为了和onHttpError使用相同的错误处理，此处不能直接使用super.onError
               showError(error);
           }
       });
   }

   public void startGetData(){

   }

   public  void  getDataOnCompleted(){
       if (mPageInfo!=null){
           if (isLastPagerData(mPageInfo) || mDatas.isEmpty()) {
               setRefreshAndLoadEnable(true,false);
           } else {
               setRefreshAndLoadEnable(true,true);
           }
       }
       else {
           setRefreshAndLoadEnable(true,false);
       }

   }
    protected void handleDataResp(DataResp<List<DataType>> resp, boolean isRefresh) {
        int code = resp.getCode();
        if (HttpResultCode.REQUEST_SUCCESS.getCode()==code) {
            if (isRefresh) {
                mDatas.clear();
            }
            renderDataRespResponse(mDatas, resp);
            afterDataLoaded(mDatas);
            notifyListDataSetChanged();
        } else {
            onHttpError((NetworkResponse) resp);
        }

    }
    protected void renderDataRespResponse(List<DataType> mDatas, DataResp<List<DataType>> resps) {
        if (resps.getData() != null) {
            mDatas.addAll(resps.getData());
        }
    }

   protected void setRefreshAndLoadEnable(boolean isPull,boolean isLoadMore) {

   }

   protected boolean isLastPagerData(PageInfo pageInfo) {
       return pageInfo != null && pageInfo.getTotalPages() > 0 && (mCurrentPage ==
               pageInfo.getTotalPages());
   }

   public void resetPullToRefreshListView(){

   }

   public void getDataOnNext(NetworkResponse resp,boolean isRefresh){
       if (resp instanceof BaseListResp) {
           handleListResponse((BaseListResp<DataType>) resp,isRefresh);

       } else if (resp instanceof BasePageListData) {
           handlePageListResponse((BasePageListData<PageData<DataType>>) resp, isRefresh);
       }
       else if (resp instanceof  DataResp){
           handleDataResp((DataResp<List<DataType>>) resp,isRefresh);
       }
   }

    protected void handlePageListResponse(BasePageListData<PageData<DataType>> resp, boolean isRefresh) {
//        if (resp != null) {
//            int code = resp.getCode();
//            if (HttpResultCode.REQUEST_SUCCESS.getCode()==code) {
//                if (resp.getPageDatas() != null) {
//                    mPageInfo = resp.getPageDatas().getPageInfo();
//                    if (isRefresh) {
//                        mDatas.clear();
//                    }
//                    renderBasicPageDatas(mDatas, (BasePageListData<DataType>) resp);
//                    afterDataLoaded(mDatas);
//                    notifyListDataSetChanged();
//                } else {
//                    if (isRefresh) {
//                        mDatas.clear();
//                    }
//                    renderEmptyResultDatas(mDatas, isRefresh);
//                    afterDataLoaded(mDatas);
//                    notifyListDataSetChanged();
//                }
//            } else {
//                onHttpError((NetworkResponse) resp);
//            }
//        } else {
//            ToastUtil.showToast("网络异常");
//        }

    }

    /**
     * 提供默认的内容为空的处理</br>
     * 服务端提示，内容为空</br>
     *
     * @param mDatas    要刷新的数据
     * @param isRefresh 刷新标志 如果为true时，会清空缓存，然后刷新，false时不会清空之前的缓存
     */
    protected void renderEmptyResultDatas(List<DataType> mDatas, boolean isRefresh) {
        if (isRefresh) {
            mDatas.clear();
        }
    }

    protected void handleListResponse(BaseListResp<DataType> resp, boolean isRefresh) {
        int code = resp.getCode();
        if (HttpResultCode.REQUEST_SUCCESS.getCode()==code) {
            if (isRefresh) {
                mDatas.clear();
            }
            renderListResponse(mDatas, resp);
            afterDataLoaded(mDatas);
            notifyListDataSetChanged();
        } else {
            onHttpError((NetworkResponse) resp);
        }

    }
    protected void renderListResponse(List<DataType> mDatas, BaseListResp<DataType> resps) {
        if (resps.getDatas() != null && !resps.getDatas().isEmpty()) {
            mDatas.addAll(resps.getDatas());
        }
    }

   protected void handleOtherNetworkResponse(NetworkResponse resp, boolean isRefresh) {
        if (isRefresh){
            mDatas.clear();
        }
       handleListData(mDatas, resp);
       afterDataLoaded(mDatas);
       notifyListDataSetChanged();

   }
   protected void handleNetworkResponse(BaseListResp<DataType> resp, boolean isRefresh) {
       int code = resp.getCode();
       if (HttpResultCode.REQUEST_SUCCESS.getCode()==code) {
           if ( isRefresh) {
               mDatas.clear();
           }
           renderListData(mDatas, resp);
           afterDataLoaded(mDatas);
           notifyListDataSetChanged();
       } else {
           onHttpError((NetworkResponse) resp);
       }

   }
   protected void renderListData(List<DataType> mDatas, BaseListResp<DataType> dataResps) {
       if (dataResps != null && dataResps.getDatas() != null) {
           mDatas.addAll(dataResps.getDatas());
       }
   }

   protected void handleListData(List<DataType> mDatas, NetworkResponse response) {

   }



   protected void onHttpError(NetworkResponse resp) {
       showError(resp);
   }

   protected void showError(NetworkResponse resp) {
       if (resp instanceof BaseResp) {
           String errorMsg = ((BaseResp) resp).getMessage();
           showError(errorMsg);
       } else {
           showError("网络异常");
       }

   }
   protected void showError(String error) {
       ToastUtil.showToast(error);
   }

   protected void renderBasicPageDatas(List<DataType> mDatas, PageData<DataType> datas) {
       if (datas.getDatas() != null && !datas.getDatas().isEmpty()) {
           mDatas.addAll(datas.getDatas());
       }
   }




   public void onRefreshView() {
       isRefresh(true);
       requestPageData(1,true);

   }



   protected void isRefresh(boolean isFresh) {
   }

   protected void isLoadMore(boolean isLoadMore) {

   }

   public void loadMore() {
       isLoadMore(true);
       if (mPageInfo != null) {
           if (mCurrentPage >= mPageInfo.getTotalPages()) {
               ToastUtil.showToast(getResources().getString(R.string.already_last_page));
           } else {
               requestPageData(mCurrentPage + 1, false);
           }
       } else {
           requestPageData(1, false);
       }
   }

   /**
    * 提供默认的创建刷新界面的处理</br>
    *
    * @param parent 向parent设置滑动布局 内容
    */
   @SuppressLint("WrongViewCast")
   protected void onCreateContentBody(ViewGroup parent) {


   }



   protected void afterDataLoaded(List<DataType> mDatas) {

   }



   protected void notifyListDataSetChanged() {
       if (mBaseAdapter != null) {
           mBaseAdapter.notifyDataSetChanged();
       }
       if (mDatas.isEmpty()) {

       } else {
           // xListView.setEmptyStatus(false);
       }

   }






}
